package com.hyy.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;


public class JdbcUtil {
	private static String JDBC_DRIVER;
	private static String DB_URL;
	private static String USERNAME;
	private static String PASSWORD;

	static {
		loadConfig();
	}

	public static void loadConfig() {
		try {
			InputStream inStream = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
			Properties prop = new Properties();
			prop.load(inStream);
			USERNAME = prop.getProperty("username");
			PASSWORD = prop.getProperty("password");
			JDBC_DRIVER = prop.getProperty("jdbcDriver");
			DB_URL = prop.getProperty("dbUrl");
		} catch (Exception e) {
			throw new RuntimeException("读取数据库配置文件异常！", e);
		}
	}

	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(JDBC_DRIVER); // 注册驱动
			conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); // 获取连接
		} catch (Exception e) {
			throw new RuntimeException("get connection error!", e);
		}
		return conn;
	}


	/**
	 * 释放资源
	 */
	public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		release(conn,pstmt);
	}
	public static void release(Connection conn, PreparedStatement pstmt) {
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

